﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace robotics_ex_1_3
{
    class NewPolygonFinder
    {
        public static List<Point> extract_polygon(List<Line> freeSpaceLines)
        {
            if (freeSpaceLines.Count < 3)
            {
                throw new Exception("Polygon must have at least 3 edges");
            }

            List<Point> polygon_vertices = new List<Point>();

            for (Int32 i = 0; i < (freeSpaceLines.Count - 1); i++)
            {
                polygon_vertices.Add(get_intersection(freeSpaceLines[i], freeSpaceLines[i + 1]));
            }

            polygon_vertices.Add(get_intersection(freeSpaceLines[freeSpaceLines.Count - 1], freeSpaceLines[0]));

            return polygon_vertices;
        }

        public static Point get_intersection(Line line1, Line line2)
        {
            if (line1.Angle == line2.Angle)
            {
                Console.WriteLine("Parallel lines don't intersect");
                throw new ArgumentException();
            }

            double b1 = Math.Tan(line1.Angle);
            double c1 = -(line1.StartPoint.X + b1*line1.StartPoint.Y);
            double b2 = Math.Tan(line2.Angle);
            double c2 = -(line2.StartPoint.X + b2 * line2.StartPoint.Y);
            double y1 = 0;
            bool use_two = false;
            if (line1.StartPoint.Y == line1.EndPoint.Y)
            {
                y1 = line1.EndPoint.Y;
                use_two = true;
            }
            if (line2.StartPoint.Y == line2.EndPoint.Y)
            {
                y1 = line2.StartPoint.Y;
            }
            if (line1.StartPoint.Y != line1.EndPoint.Y && line2.StartPoint.Y != line2.EndPoint.Y)
            {
                y1 = (c2 - c1) / (b1 - b2);
            }
            double x1=0;
            if (line1.StartPoint.X == line1.EndPoint.X)
            {
                x1=line1.EndPoint.X;
            }
            if(line2.StartPoint.X==line2.EndPoint.X)
            {
                x1 = line2.StartPoint.X;
            }
            if (line1.StartPoint.X != line1.EndPoint.X && line2.StartPoint.X != line2.EndPoint.X)
            {
                x1 = -(b1 * y1 + c1);
                if (use_two)
                {
                    x1 = -(b2 * y1 + c2);
                }
            }
            Console.WriteLine("Line: ("+line1.StartPoint.X+","+line1.StartPoint.Y+")-("+line1.EndPoint.X+","+line1.EndPoint.Y+") and line: ("+line2.StartPoint.X+","+line2.StartPoint.Y+")-("+line2.EndPoint.X+","+line2.EndPoint.Y+") intersect at: ("+x1+","+y1+")");
            return new Point(x1, y1);
        }
    }
}
